﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XingFuStudio.Pioneer.Entity;
using System.Configuration;
using System.IO;
using System.Xml.Linq;

namespace XingFuStudio.Pioneer.Data {
    /// <summary>
    /// 开心网帐户的好友信息数据访问类
    /// </summary>
    public class DbFriendInAccount {

        /// <summary>
        /// 存放Xml文档的文件夹
        /// </summary>
        private readonly string xmlFolder = String.Empty;
        /// <summary>
		/// 存放Xml文档路径
		/// </summary>
		private readonly string xmlPath = String.Empty;

		/// <summary>
		/// 创建一个<see cref="DbFriendInAccount"/>实例
		/// </summary>
        public DbFriendInAccount() {
            //获取XML文档所在的文件夹
            this.xmlFolder = ConfigurationManager.AppSettings["XmlFolder"];

            //判断是否设置了数据文件夹
            if (String.IsNullOrEmpty(xmlFolder)) {
                this.xmlFolder = "Data";
            }

            //判断设置的数据文件夹是否存在
            if (!Directory.Exists(this.xmlFolder)) {
                //不存在,创建数据文件夹
                Directory.CreateDirectory(this.xmlFolder);
            }

            //获取XML文件名称
            string xmlFile =  ConfigurationManager.AppSettings["FriendInAccountXml"];

            //判断是否设置了XML文件名称
            if (String.IsNullOrEmpty(xmlFile)) {
                xmlFile = "FriendInAccount.xml";
            }

            this.xmlPath = this.xmlFolder + "\\" + xmlFile;

            //判断指定的数据文件是否存在
            if (!File.Exists(xmlPath)) {
                //初始化指定的数据文件
                XDocument xmlDoc = new XDocument(
                    new XElement("Accounts"));

                //存储数据文件
                xmlDoc.Save(xmlPath);
            }
		}

        /// <summary>
        /// 修改帐户的好友
        /// </summary>
        /// <param name="email"></param>
        /// <param name="friends"></param>
        /// <returns></returns>
        public bool ModifyAccountFriends(string email, List<FriendInfo> friends) {
            //移除全部好友
            this.RemoveAllFriendsFromAccount(email);

            //声明标识
            bool flag = false;

            try {
                //获取现有Xml文档数据
                XElement xmlContent = XElement.Load(xmlPath);

                //创建新的帐户Xml对象
                XElement newAccount = new XElement("Account", new XAttribute("Email", email));

                //遍历好友
                foreach (FriendInfo friend in friends) {
                    //初始化好友Xml对象
                    XElement xmlFriend = new XElement("Friend", new XAttribute("FriendId", friend.UserId));
                    //将好友Xml对象添加到帐户Xml对象中
                    newAccount.Add(xmlFriend);
                }

                //添加到现有Xml中
                xmlContent.Add(newAccount);
                //保存Xml
                xmlContent.Save(xmlPath);

                //添加成功
                flag = true;
            } catch (Exception ex) {
                //添加失败，记录系统运行日志
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }

            //返回查询结果
            return flag;
        }

        /// <summary>
        /// 移除指定帐户的全部好友
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        private bool RemoveAllFriendsFromAccount(string email) {
            //声明标识
            bool flag = false;

            try {
                //获取现有Xml文档数据
                XElement xmlContent = XElement.Load(xmlPath);

                //删除满足条件的帐户信息
                xmlContent.Elements("Account")
                    .Where(s => s.Attribute("Email").Value.ToLower() == email.ToLower())
                    .Remove();

                //存储修改后的结果
                xmlContent.Save(xmlPath);

                flag = true;
            } catch (Exception ex) {
                //添加失败，记录系统运行日志
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }

            //返回查询结果
            return flag;
        }

        /// <summary>
        /// 获取指定帐户的全部好友
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public List<FriendInfo> GetAccountFriends(string email) {
            //初始化一个好友数据访问类对象，目的是保证好友Xml文件的存在
            DbFriend dbFriend = new DbFriend();

            List<FriendInfo> list = new List<FriendInfo>();

            try {
                //获取现有Xml文档数据
                XElement xmlContent = XElement.Load(xmlPath);

                //获取XML文件名称
                string xmlFriendFile = ConfigurationManager.AppSettings["FriendXml"];
                //判断是否设置了XML文件名称
                if (String.IsNullOrEmpty(xmlFriendFile)) {
                    xmlFriendFile = "Friends.xml";
                }
                //获取现有好友Xml文档数据
                XElement xmlFriends = XElement.Load(this.xmlFolder + "\\" + xmlFriendFile);
                //获取当前帐户的好友
                XElement xmlMyFriends = xmlContent.Elements("Account")
                    .First(s => s.Attribute("Email").Value.ToLower() == email.ToLower());

                if (xmlMyFriends != null) {
                    var res = from f in xmlFriends.Elements("Friend")
                            from mf in xmlMyFriends.Elements("Friend")
                            where f.Attribute("FriendId").Value == mf.Attribute("FriendId").Value
                            select f;

                    //赋值查询信息
                    foreach (XElement item in res) {
                        FriendInfo info = new FriendInfo();

                        //赋值信息
                        info.UserId = item.Attribute("FriendId").Value;
                        info.UserName = item.Element("FriendName").Value;
                        info.Gender = (Gender)Convert.ToInt32(item.Element("Gender").Value);

                        list.Add(info);
                    }
                }
            } catch (Exception ex) {
                //添加失败，记录系统运行日志
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }

            return list;
        }
    }
}
